/**
 * SmarTest Studio - 项目浏览器功能
 * 合并了面板折叠功能和测试用例/测试任务管理功能
 */

import { showNotification } from "./utils.js";
import { getProjectOwner, getProjectName } from "./utils.js";
import { openTestCase } from "./activity-editor.js";
import http from './http-client.js';

window.projectOwner = undefined;
window.projectName = undefined;
window.projectPath = undefined;

document.addEventListener('DOMContentLoaded', function() {
    // 初始化折叠面板
    initCollapsiblePanels();
    
    // 监听面板折叠/收起事件
    setupPanelListeners();
    
    // 监听测试用例和测试任务新增和刷新事件
    setupPanelButtons();
});

/**
 * 初始化折叠面板功能
 */
function initCollapsiblePanels() {
    // 获取所有可折叠的面板标题
    const collapsibleHeaders = document.querySelectorAll('.panel-header.collapsible');
    
    // 为每个可折叠标题添加事件监听
    collapsibleHeaders.forEach(header => {
        // 获取目标面板体
        const targetId = header.getAttribute('data-bs-target');
        const targetPanel = document.querySelector(targetId);
        const headerActions = header.querySelector('.header-actions');
        
        // 监听Bootstrap折叠事件
        if (targetPanel) {
            targetPanel.addEventListener('show.bs.collapse', function() {
                header.setAttribute('aria-expanded', 'true');
            });
            
            targetPanel.addEventListener('hide.bs.collapse', function() {
                header.setAttribute('aria-expanded', 'false');
            });
        }
    });
}

/**
 * 设置面板展开/折叠事件监听
 */
function setupPanelListeners() {
    // 测试用例面板
    const testcasesPanel = document.getElementById('testcases-body');
    if (testcasesPanel) {
        testcasesPanel.addEventListener('show.bs.collapse', function() {
            loadTestCases();
        });
    }
    
    // 测试任务面板
    const testtasksPanel = document.getElementById('testtasks-body');
    if (testtasksPanel) {
        testtasksPanel.addEventListener('show.bs.collapse', function() {
            loadTestTasks();
        });
    }
}

/**
 * 设置添加按钮和刷新按钮的事件处理
 */
function setupPanelButtons() {
    // 测试用例添加按钮
    const addTestcaseBtn = document.querySelector('.panel-header[data-bs-target="#testcases-body"] .add-btn');
    if (addTestcaseBtn) {
        addTestcaseBtn.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡，避免触发折叠
            showCreateTestcaseDialog();
        });
    }
    
    // 测试用例刷新按钮
    const refreshTestcaseBtn = document.querySelector('.panel-header[data-bs-target="#testcases-body"] .refresh-btn');
    if (refreshTestcaseBtn) {
        refreshTestcaseBtn.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡，避免触发折叠
            loadTestCases();
        });
    }
    
    // 测试任务添加按钮
    const addTesttaskBtn = document.querySelector('.panel-header[data-bs-target="#testtasks-body"] .add-btn');
    if (addTesttaskBtn) {
        addTesttaskBtn.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡，避免触发折叠
            showCreateTesttaskDialog();
        });
    }
    
    // 测试任务刷新按钮
    const refreshTesttaskBtn = document.querySelector('.panel-header[data-bs-target="#testtasks-body"] .refresh-btn');
    if (refreshTesttaskBtn) {
        refreshTesttaskBtn.addEventListener('click', function(e) {
            e.stopPropagation(); // 阻止事件冒泡，避免触发折叠
            loadTestTasks();
        });
    }
}

/**
 * 加载测试用例列表
 */
function loadTestCases() {
    const testcasesList = document.getElementById('project-testcases');
    if (!testcasesList) return;
    
    // 显示加载指示器
    testcasesList.innerHTML = '<div class="loading-indicator"><i class="bi bi-arrow-repeat spin"></i> 正在加载...</div>';
    
    // 获取项目Owner和Name
    const projectOwner = getProjectOwner();
    const projectName = getProjectName();
    
    // 发送UiTest请求获取测试用例列表
    http.get(`/api/projects?api=load_test_cases&owner=${projectOwner}&name=${projectName}`)
        .then(response => {
            // 渲染测试用例列表
            renderTestCases(testcasesList, response.data);
        })
        .catch(error => {
            console.error('加载测试用例出错:', error);
            testcasesList.innerHTML = `<div class="error-message"><i class="bi bi-exclamation-triangle"></i> 加载失败: ${error.message}</div>`;
        });
}

/**
 * 渲染测试用例列表
 * @param {HTMLElement} container - 容器元素
 * @param {Array} testNames - 测试用例名
 */
function renderTestCases(container, testNames) {
    if (!testNames || testNames.length === 0) {
        container.innerHTML = '<div class="empty-message"><i class="bi bi-info-circle"></i> 暂无测试用例</div>';
        return;
    }
    
    let html = '';
    testNames.forEach(testName => {
        html += `
        <li class="file-item" data-test-name="${testName}">
            <div class="file-item-content">
                <span class="file-name">${testName}</span>
            </div>
        </li>`;
    });
    
    container.innerHTML = html;
    
    // 添加测试用例项的点击事件
    setupTestcaseItemEvents();
}

/**
 * 设置测试用例项的事件
 */
function setupTestcaseItemEvents() {
    // 测试用例点击事件
    const testcaseItems = document.querySelectorAll('#project-testcases .file-item');
    testcaseItems.forEach(item => {
        item.addEventListener('click', function(e) {
            if (!e.target.closest('.file-actions')) {
                // 移除其他测试用例的选中状态
                document.querySelectorAll('#project-testcases .file-item').forEach(el => {
                    el.classList.remove('active');
                });
                
                // 添加当前测试用例的选中状态
                this.classList.add('active');
                
                const testName = this.getAttribute('data-test-name');
                // 设置flow-container的data-current-test属性
                document.querySelector('.flow-container').setAttribute('data-current-test', testName);
                openTestCase(testName);
            }
        });
        
        // // 编辑按钮
        // const editBtn = item.querySelector('.edit-testcase');
        // if (editBtn) {
        //     editBtn.addEventListener('click', function(e) {
        //         e.stopPropagation();
        //         const testName = item.getAttribute('data-test-name');
        //         editTestcase(testName);
        //     });
        // }
        
        // // 删除按钮
        // const deleteBtn = item.querySelector('.delete-testcase');
        // if (deleteBtn) {
        //     deleteBtn.addEventListener('click', function(e) {
        //         e.stopPropagation();
        //         const testName = item.getAttribute('data-test-name');
        //         deleteTestcase(testName);
        //     });
        // }
    });
}

/**
 * 加载测试任务列表
 */
function loadTestTasks() {
    const testtasksList = document.getElementById('project-testtasks');
    if (!testtasksList) return;
    
    // 显示加载指示器
    testtasksList.innerHTML = '<div class="loading-indicator"><i class="bi bi-arrow-repeat spin"></i> 正在加载...</div>';
    
    // 获取项目Owner和Name
    const projectOwner = getProjectOwner();
    const projectName = getProjectName();
    
    // 发送UiTest请求获取测试任务列表
    http.get(`/api/projects?api=get_test_tasks&owner=${projectOwner}&name=${projectName}`)
        .then(response => {
            // 渲染测试任务列表
            renderTesttasks(testtasksList, response.data);
        })
        .catch(error => {
            console.error('加载测试任务出错:', error);
            testtasksList.innerHTML = `<div class="error-message"><i class="bi bi-exclamation-triangle"></i> 加载失败: ${error.message}</div>`;
        });
}

/**
 * 渲染测试任务列表
 * @param {HTMLElement} container - 容器元素
 * @param {Array} testtasks - 测试任务数据
 */
function renderTesttasks(container, testtasks) {
    if (!testtasks || testtasks.length === 0) {
        container.innerHTML = '<div class="empty-message"><i class="bi bi-info-circle"></i> 暂无测试任务</div>';
        return;
    }
    
    let html = '';
    testtasks.forEach(testtask => {
        html += `
        <li class="file-item" data-id="${testtask}">
            <div class="file-item-content">
                <span class="file-name">${testtask}</span>
            </div>
        </li>`;
    });
    
    container.innerHTML = html;
    
    // 添加测试任务项的点击事件
    setupTesttaskItemEvents();
}

/**
 * 设置测试任务项的事件
 */
function setupTesttaskItemEvents() {
    // 测试任务点击事件
    const testtaskItems = document.querySelectorAll('#project-testtasks .file-item');
    testtaskItems.forEach(item => {
        item.addEventListener('click', function(e) {
            if (!e.target.closest('.file-actions')) {
                const testtaskId = this.getAttribute('data-id');
                openTesttask(testtaskId);
            }
        });
        
        // // 编辑按钮
        // const editBtn = item.querySelector('.edit-testtask');
        // if (editBtn) {
        //     editBtn.addEventListener('click', function(e) {
        //         e.stopPropagation();
        //         const testtaskId = item.getAttribute('data-id');
        //         editTesttask(testtaskId);
        //     });
        // }
        
        // // 删除按钮
        // const deleteBtn = item.querySelector('.delete-testtask');
        // if (deleteBtn) {
        //     deleteBtn.addEventListener('click', function(e) {
        //         e.stopPropagation();
        //         const testtaskId = item.getAttribute('data-id');
        //         deleteTesttask(testtaskId);
        //     });
        // }
    });
}

/**
 * 显示创建测试用例对话框
 */
function showCreateTestcaseDialog() {
    // 创建对话框HTML
    const dialogHTML = `
    <div class="modal fade" id="createTestcaseModal" tabindex="-1" aria-labelledby="createTestcaseModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createTestcaseModalLabel">新建测试用例</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="createTestcaseForm">
                        <div class="mb-3">
                            <label for="testcaseName" class="form-label">测试用例名称</label>
                            <input type="text" class="form-control" id="testcaseName" required>
                        </div>
                        <div class="mb-3">
                            <label for="testcaseDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="testcaseDescription" rows="3"></textarea>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="createTestcaseBtn">创建</button>
                </div>
            </div>
        </div>
    </div>`;
    
    // 添加对话框到DOM
    document.body.insertAdjacentHTML('beforeend', dialogHTML);
    
    // 获取对话框元素
    const modalEl = document.getElementById('createTestcaseModal');
    const modal = new bootstrap.Modal(modalEl);
    
    // 显示对话框
    modal.show();
    
    // 绑定创建按钮事件
    const createBtn = document.getElementById('createTestcaseBtn');
    createBtn.addEventListener('click', function() {
        newTestCase();
    });
    
    // 对话框关闭后移除
    modalEl.addEventListener('hidden.bs.modal', function() {
        modalEl.remove();
    });
}

/**
 * 创建测试用例
 */
function newTestCase() {
    // 获取表单数据
    const testName = document.getElementById('testcaseName').value.trim();
    const testDescription = document.getElementById('testcaseDescription').value.trim();
    if (!testName) {
        alert('请输入测试用例名称');
        return;
    }
    const projectOwner = getProjectOwner();
    const projectName = getProjectName();
    
    // 创建测试用例数据
    const requestData = {
        api: 'new_test_case',
        owner: projectOwner,
        name: projectName,
        test: testName,
        description: testDescription,
    };
    
    // 发送UiTest请求创建测试用例
    http.post(`/api/projects`, requestData)
    .then(() => {
        // 关闭对话框
        const modal = bootstrap.Modal.getInstance(document.getElementById('createTestcaseModal'));
        modal.hide();
        
        // 重新加载测试用例列表
        loadTestCases();
        
        // 显示成功消息
        showNotification('success', '测试用例创建成功');
    })
    .catch(error => {
        console.error('创建测试用例出错:', error);
        showNotification('error', `创建失败: ${error.message}`);
    });
}

/**
 * 显示创建测试任务对话框
 */
function showCreateTesttaskDialog() {
    // 创建对话框HTML
    const dialogHTML = `
    <div class="modal fade" id="createTesttaskModal" tabindex="-1" aria-labelledby="createTesttaskModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="createTesttaskModalLabel">新建测试任务</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"></button>
                </div>
                <div class="modal-body">
                    <form id="createTesttaskForm">
                        <div class="mb-3">
                            <label for="testtaskName" class="form-label">测试任务名称</label>
                            <input type="text" class="form-control" id="testtaskName" required>
                        </div>
                        <div class="mb-3">
                            <label for="testtaskDescription" class="form-label">描述</label>
                            <textarea class="form-control" id="testtaskDescription" rows="3"></textarea>
                        </div>
                        <div class="mb-3">
                            <label for="testtaskDevice" class="form-label">目标设备</label>
                            <select class="form-select" id="testtaskDevice">
                                <option value="" selected>选择设备...</option>
                                <!-- 设备列表将通过API动态加载 -->
                            </select>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="createTesttaskBtn">创建</button>
                </div>
            </div>
        </div>
    </div>`;
    
    // 添加对话框到DOM
    document.body.insertAdjacentHTML('beforeend', dialogHTML);
    
    // 获取对话框元素
    const modalEl = document.getElementById('createTesttaskModal');
    const modal = new bootstrap.Modal(modalEl);
    
    // 加载设备列表
    loadDeviceOptions();
    
    // 显示对话框
    modal.show();
    
    // 绑定创建按钮事件
    const createBtn = document.getElementById('createTesttaskBtn');
    createBtn.addEventListener('click', function() {
        createTesttask();
    });
    
    // 对话框关闭后移除
    modalEl.addEventListener('hidden.bs.modal', function() {
        modalEl.remove();
    });
}

/**
 * 加载设备选项
 */
function loadDeviceOptions() {
    const deviceSelect = document.getElementById('testtaskDevice');
    if (!deviceSelect) return;
    
    // 发送UiTest请求获取设备列表
    fetch('/api/devices')
        .then(response => {
            if (!response.ok) {
                throw new Error('获取设备列表失败');
            }
            return response.json();
        })
        .then(data => {
            // 添加设备选项
            data.forEach(device => {
                const option = document.createElement('option');
                option.value = device.id;
                option.textContent = device.name;
                deviceSelect.appendChild(option);
            });
        })
        .catch(error => {
            console.error('加载设备列表出错:', error);
            deviceSelect.innerHTML = '<option value="" selected>加载设备失败</option>';
        });
}

/**
 * 创建测试任务
 */
function createTesttask() {
    // 获取表单数据
    const name = document.getElementById('testtaskName').value.trim();
    const description = document.getElementById('testtaskDescription').value.trim();
    const deviceId = document.getElementById('testtaskDevice').value;
    
    if (!name) {
        alert('请输入测试任务名称');
        return;
    }
    
    // 获取项目ID
    const projectId = document.querySelector('.project-path .path').getAttribute('data-id');
    
    // 创建测试任务数据
    const testtaskData = {
        name: name,
        description: description,
        project_id: projectId,
        device_id: deviceId || null
    };
    
    // 发送UiTest请求创建测试任务
    fetch(`/api/projects/${projectId}/testtasks`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(testtaskData)
    })
    .then(response => {
        if (!response.ok) {
            throw new Error('创建测试任务失败');
        }
        return response.json();
    })
    .then(data => {
        // 关闭对话框
        const modal = bootstrap.Modal.getInstance(document.getElementById('createTesttaskModal'));
        modal.hide();
        
        // 重新加载测试任务列表
        loadTestTasks();
        
        // 显示成功消息
        showNotification('success', '测试任务创建成功');
    })
    .catch(error => {
        console.error('创建测试任务出错:', error);
        showNotification('error', `创建失败: ${error.message}`);
    });
}